package com.cino.protocol;

import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

public class HttpServer {

    public void start(String hostname, Integer port){
        Tomcat tomcat = new Tomcat();
        String contextPath = "";

        Context context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());

        Host host = tomcat.getHost();
        host.addChild(context);

        Service service = tomcat.getService();
        Engine engine = tomcat.getEngine();
        Connector connector = tomcat.getConnector();

        service.setContainer(engine);
        service.addConnector(connector);

        // 确保 DispatcherServlet 类名拼写正确
        tomcat.addServlet(contextPath, "dispatcher", new DispatcherServlet());
        context.addServletMappingDecoded("/*", "dispatcher");

        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }
}
